package com.xxc.hs.db;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;


import com.xxc.hs.bean.DataInfo;
import com.xxc.hs.bean.DataType;

import java.util.ArrayList;
import java.util.List;

@SuppressWarnings("ALL")
public class DataHelper extends SQLiteOpenHelper {
    private static DataHelper helper;
    private static final String DB_NAME = "data.db";
    private static final int VERSION = 1;
    private static final String TABLE_NAME = "data_table";

    // 列名常量
    private static final String COL_ID = "data_id";
    private static final String COL_TEMP = "temp_value";
    private static final String COL_HUM = "hum_value";
    private static final String COL_SMOKE = "smoke_value";
    private static final String COL_FIRE = "fire_value";
    private static final String COL_TIME = "time";

    private DataHelper(Context context) {
        super(context, DB_NAME, null, VERSION);
    }

    public synchronized static DataHelper getInstance(Context context) {
        if (null == helper) {
            helper = new DataHelper(context.getApplicationContext());
        }
        return helper;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE " + TABLE_NAME + " (" +
                COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                COL_TEMP + " TEXT, " +
                COL_HUM + " TEXT, " +
                COL_SMOKE + " INTEGER, " +
                COL_FIRE + " INTEGER, " +
                COL_TIME + " TEXT)");
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
    }

    /**
     * 添加数据
     */
    public void InsertData(DataInfo dataInfo) {
        SQLiteDatabase db = getWritableDatabase();

        try (db) {
            ContentValues values = new ContentValues();
            values.put(COL_TEMP, dataInfo.getTemp());
            values.put(COL_HUM, dataInfo.getHum());
            values.put(COL_SMOKE, dataInfo.getSmoke());
            values.put(COL_FIRE, dataInfo.getFire());
            values.put(COL_TIME, dataInfo.getTime());

            db.insert(TABLE_NAME, null, values);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据传入的类型和身份获取数据
     */
    @SuppressLint("Range")
    public List<DataInfo> GetDataByType(int limit, DataType... dataTypes) {
        List<DataInfo> dataInfoList = new ArrayList<>();
        SQLiteDatabase db = getReadableDatabase();
        Cursor cursor = null;

        try {
            // 根据类型构建SQL查询语句
            StringBuilder selection = new StringBuilder();
            List<String> selectionArgs = new ArrayList<>();

            // 根据不同类型构建不同的查询条件
            if (dataTypes != null && dataTypes.length > 0) {
                for (int i = 0; i < dataTypes.length; i++) {
                    // 将DataType映射到数据库列名
                    String columnName = mapDataTypeToColumnName(dataTypes[i]);
                    if (columnName != null) {
                        selection.append(columnName).append(" IS NOT NULL AND ")
                                .append(columnName).append(" != ''");
                        if (i < dataTypes.length - 1) {
                            selection.append(" OR ");
                        }
                    }
                }
            }

            cursor = db.query(
                    TABLE_NAME,
                    null,
                    selection.length() > 0 ? selection.toString() : null,
                    selectionArgs.toArray(new String[0]),
                    null,
                    null,
                    COL_ID + " DESC", // 按ID降序（最新数据在前）
                    String.valueOf(limit)
            );

            // 解析结果
            if (cursor != null && cursor.moveToFirst()) {
                do {
                    DataInfo dataInfo = new DataInfo();
                    dataInfo.setData_id(cursor.getInt(cursor.getColumnIndex(COL_ID)));
                    dataInfo.setTemp(cursor.getString(cursor.getColumnIndex(COL_TEMP)));
                    dataInfo.setHum(cursor.getString(cursor.getColumnIndex(COL_HUM)));
                    dataInfo.setSmoke(cursor.getInt(cursor.getColumnIndex(COL_SMOKE)));
                    dataInfo.setFire(cursor.getInt(cursor.getColumnIndex(COL_FIRE)));
                    dataInfo.setTime(cursor.getString(cursor.getColumnIndex(COL_TIME)));
                    dataInfoList.add(dataInfo);
                } while (cursor.moveToNext());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != cursor) {
                cursor.close();
            }
            db.close();
        }
        return dataInfoList;
    }


    /**
     * 获取指定数量历史数据
     */
    @SuppressLint("Range")
    public List<DataInfo> getRecentData(int limit) {
        List<DataInfo> dataInfoList = new ArrayList<>();
        SQLiteDatabase db = getReadableDatabase();
        Cursor cursor = null;

        try {
            cursor = db.query(
                    TABLE_NAME,
                    null,
                    null,
                    null,
                    null,
                    null,
                    COL_ID + " DESC", // 按ID降序（最新数据在前）
                    String.valueOf(limit)
            );

            // 解析结果
            if (cursor != null && cursor.moveToFirst()) {
                do {
                    DataInfo dataInfo = new DataInfo();
                    dataInfo.setData_id(cursor.getInt(cursor.getColumnIndex(COL_ID)));
                    dataInfo.setTemp(cursor.getString(cursor.getColumnIndex(COL_TEMP)));
                    dataInfo.setHum(cursor.getString(cursor.getColumnIndex(COL_HUM)));
                    dataInfo.setTime(cursor.getString(cursor.getColumnIndex(COL_TIME)));
                    dataInfoList.add(dataInfo);
                } while (cursor.moveToNext());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != cursor) {
                cursor.close();
            }
            db.close();
        }
        return dataInfoList;
    }


    /**
     * 获取所有温度数据
     */
    @SuppressLint("Range")
    public List<DataInfo> getTemperatureData(int type) {
        if (type == 1) {
            return GetDataByType(40, DataType.TEMPERATURE);
        }
        return GetDataByType(20, DataType.TEMPERATURE);
    }

    /**
     * 获取所有湿度数据
     */
    @SuppressLint("Range")
    public List<DataInfo> getHumidityData(int type) {
        if (type == 1) {
            return GetDataByType(40, DataType.HUMIDITY);
        }
        return GetDataByType(20, DataType.HUMIDITY);
    }

    /**
     * 获取所有烟雾数据
     */
    @SuppressLint("Range")
    public List<DataInfo> getSmokeData(int type) {
        if (type == 1) {
            return GetDataByType(40, DataType.SMOKE);
        }
        return GetDataByType(20, DataType.SMOKE);
    }

    /**
     * 获取所有火焰数据
     */
    @SuppressLint("Range")
    public List<DataInfo> getFireData(int type) {
        if (type == 1) {
            return GetDataByType(40, DataType.FIRE);
        }
        return GetDataByType(20, DataType.FIRE);
    }

    /**
     * 将DataType枚举映射到数据库列名
     */
    private String mapDataTypeToColumnName(DataType dataType) {
        switch (dataType) {
            case TEMPERATURE:
                return COL_TEMP;
            case HUMIDITY:
                return COL_HUM;
            case SMOKE:
                return COL_SMOKE;
            case FIRE:
                return COL_FIRE;
            default:
                return null;
        }
    }

}
